var PeopleMedia = PeopleMedia || {};

PeopleMedia.WebSyncServer = PeopleMedia.WebSyncServer || {
    Client: null,
    WebSyncUrl: "http://external.RTN.peoplemedia.com/websync.ashx",
    Init: function () {
        if (this.Client == null) {
            if (typeof (fm.websync.client) == "object") {
                // WSv3
                this.Client = fm.websync.client;
            } else {
                //WSv4+
                this.Client = new fm.websync.client(this.WebSyncUrl);
            }

            if (this.Client.initialize)
                this.Client.initialize();

            this.Client.connect();
        }
    }
};

PeopleMedia.RealTimeNotificationOverlay = {
    Client: null,
    Channel: '',
    AnimationDisplay: 0,
    AnimationFadeOut: 0,
    MessagesReceived: 0,
    MessagesDisplayed: 0,
    SiteImagePath: '',
    RTNInvalidEmailEnabled: false,
    ProcessMessage: function (data) {
        if (typeof data.BatchInfo !== 'undefined') {
            PeopleMedia.RealTimeNotificationOverlay.PublishMessageReceived(data.BatchInfo);
            if (typeof data.RtnMessageInfos === 'undefined' || data.RtnMessageInfos.length === 0) {
                data.RtnMessageInfos = [];
                data.RtnMessageInfos[0] = PeopleMedia.RealTimeNotificationOverlay.ConvertSummaryMessage(data.BatchInfo);
            }
            $jq.each(data.RtnMessageInfos, function (index, objValue) {
                PeopleMedia.RealTimeNotificationOverlay.MessagesReceived++;
                $jq("#rtn_alert").queue("fx", function (next) {
                    PeopleMedia.RealTimeNotificationOverlay.ShowMessage(objValue);
                    next();
                });
            });
        }
    },
    ConvertSummaryMessage: function (data) {
        var msg = {
            "MessageType": "Summary",
            "MessageHoverText": null,
            "MessageText": data.MessageText,
            "MessageUriDisplayText": data.MessageUriDisplayText,
            "NotificationType": data.NotificationType,
            "ProfilePhotoUri": PeopleMedia.RealTimeNotificationOverlay.GetSummaryIconUri(data.NotificationType),
            "RelativeMessageUri": data.RelativeMessageUri,
            "RelativeProfileUri": data.RelativeMessageUri,
            "UserName": null
        };
        return msg;
    },
    GetSummaryIconUri: function (notificationType) {
        var prefix = PeopleMedia.RealTimeNotificationOverlay.SiteImagePath + '/images/realtimenotification/';
        switch (notificationType) {
            case "RtnProfileViewNotification":
                return prefix + "viewed-large.png";
            case "RtnFlirtNotification":
                return prefix + "flirt-large.png";
            case "RtnMessageNotification":
                return prefix + "message-large.png";
            case "RtnFavoriteAddNotification":
            case "RtnMutualFavoriteAddNotification":
                return prefix + "favorite-large.png";
            case "RtnChatRequestNotification":
                return prefix + "chat-large.png";
            default:
                return prefix + "message-large.png";
        }
    },
    ShowMessage: function (objValue) {
        if (typeof objValue !== 'undefined') {
            if (PeopleMedia.RealTimeNotificationOverlay.RTNInvalidEmailEnabled == false && objValue.NotificationType == "RtnUpdateInvalidEmail") {
                return;
            }
            var isSummary = ((typeof objValue.MessageType !== 'undefined') && objValue.MessageType === "Summary");
            PeopleMedia.RealTimeNotificationOverlay.AddStatusMessage('ShowMessage isSummary=' + isSummary.toString());
            var profileUri = (objValue.RelativeProfileUri !== null) ? objValue.RelativeProfileUri : "";
            var messageUri = (objValue.RelativeMessageUri !== null) ? objValue.RelativeMessageUri : "";
            var profilePhotoUri = (objValue.ProfilePhotoUri !== null) ? objValue.ProfilePhotoUri : "";
            var userName = (objValue.UserName !== null) ? objValue.UserName.toUpperCase() : "";
            var messageText = (objValue.MessageText !== null) ? objValue.MessageText : "";
            var messageUriDisplayText = (objValue.MessageUriDisplayText !== null) ? objValue.MessageUriDisplayText : "";
            var messageHoverText = (objValue.MessageHoverText !== null) ? objValue.MessageHoverText : "";

            var $Alert = $jq("#rtn_alert");
            if (PeopleMedia.RealTimeNotificationOverlay.RTNInvalidEmailEnabled == true && objValue.NotificationType == "RtnUpdateInvalidEmail") {
                var $EmailAlert = $Alert.clone();
                $EmailAlert.prop('id', 'rtn_alert_large');
                $EmailAlert.find('.rtnicon').remove();
                $EmailAlert.find('#rtn_username').remove();
                //$EmailAlert.find('#rtn_message').addClass('rtnEmail');
                $EmailAlert.find('[id^="rtn_message"]').prop('id', 'rtn_message_large');
                $EmailAlert.find('#close_alert').prop('id', 'close_alert_large');
                $EmailAlert.find('div.rtntool').hide();
                //var rtnContent = $jq.parseJSON(objValue.MessageText);

                $jq.ajax({
                    type: "GET",
                    url: "/v3/Notification/GetInvalidEmailNotification",
                    data: {},
                    dataType: "json",
                    success: function(result) {
                        if (result.status == "Success") {
                            $EmailAlert.find('#rtn_message_large').html(result.html);
                        } else {
                            PeopleMedia.RealTimeNotificationOverlay.CloseAlert();
                        }
                    }
                });
                
                $EmailAlert.find("#close_alert_large, #close_alert_large img").click(function (event) {
                    event.stopPropagation();
                    PeopleMedia.RealTimeNotificationOverlay.CloseAlert();
                });
                
                $EmailAlert.find("#rtn_message_large").click(function (event) {
                    event.stopPropagation();
                });

                $Alert.parent().append($EmailAlert);
                $Alert = $EmailAlert;
            }
            $Alert.attr('alt', messageHoverText);
            if (profilePhotoUri.indexOf("realtimenotification/malesilhouette.gif") != -1) {
                profilePhotoUri = PeopleMedia.RealTimeNotificationOverlay.SiteImagePath + "/contentimages/stock/nophoto-1.gif";
            }
            if (profilePhotoUri.indexOf("realtimenotification/femalesilhouette.gif") != -1) {
                profilePhotoUri = PeopleMedia.RealTimeNotificationOverlay.SiteImagePath + "/contentimages/stock/nophoto-2.gif";
            }
            if (objValue.NotificationType != "RtnUpdateInvalidEmail") {
                $Alert.find("#rtn_image").html("<a href=\"" + profileUri + "\"><img src=\"" + profilePhotoUri + "\" alt=\"\" border=\"0\" class=\"rtnuserpic\"/></a>");
                if (userName.length > 0) {
                    $Alert.find("#rtn_username").html(userName + "<br/>").unbind().click(function() { location.href = profileUri; });
                } else {
                    $Alert.find("#rtn_username").html("");
                }

                if (messageUriDisplayText.length > 0) {
                    $Alert.find("#rtn_message").html(messageText + "&nbsp;&nbsp;<a href=\"" + messageUri + "\">" + messageUriDisplayText.replace(">>", "") + "</a>");
                } else {
                    $Alert.find("#rtn_message").html("<a href=\"" + messageUri + "\">" + messageText + "</a>");
                }
                if (messageUriDisplayText.length > 0 && (messageText == "Responded to your message." || messageText == "Responded to your flirt." || messageText == "Someone responded to your flirt." || messageText == "Responded to your flirt message.")) {
                    $Alert.find("#rtn_message").html("<span id=\"echo\">ECHO!</span>" + messageText + "&nbsp;&nbsp;<a href=\"" + messageUri + "\">" + messageUriDisplayText.replace(">>", "") + "</a>");
                }
                if (messageUriDisplayText.length == 0 && (messageText == "Responded to your message." || messageText == "Responded to your flirt." || messageText == "Someone responded to your flirt." || messageText == "Responded to your flirt message.")) {
                    $Alert.find("#rtn_message").html("<span id=\"echo\">ECHO!</span><a href=\"" + messageUri + "\">" + messageText + "</a>");
                }
            }
            if (PeopleMedia.RealTimeNotificationOverlay.RTNInvalidEmailEnabled == true && objValue.NotificationType == "RtnUpdateInvalidEmail") {
                $Alert.find(".realtimenotification ").addClass("rtnlarge");
                $Alert.find('.realtimenotification.rtnlarge > div.rtnmessaging').toggleClass('rtnmessaging rtnmessaginglarge');
                $Alert.animate({ bottom: "35%", left: "25%", opacity: "+=1.0" }, 0);
                PeopleMedia.RealTimeNotificationOverlay.MessagesDisplayed++;
            } else {
                $Alert
                    .click(function () {
                        window.location.href = messageUri;
                    })
                    .animate({ bottom: "15", opacity: "+=1.0" }, 800)
                    .delay(PeopleMedia.RealTimeNotificationOverlay.AnimationDisplay)
                    .animate({ bottom: "-100", opacity: "-=1.0" }, 800);
                PeopleMedia.RealTimeNotificationOverlay.MessagesDisplayed++;
            }
        }
    },
    CloseAlert: function () {
        $jq("#rtn_alert").stop(false, true).animate({ bottom: "-100", opacity: "-=1.0" }, 800);
        $jq("#rtn_alert_large").stop(false, true).animate({ bottom: "-100", opacity: "-=1.0" }, 800);
    },
    PadZero: function (n) {
        return (n < 10) ? '0' + n : n;
    },
    Pad2Zeros: function (n) {
        if (n < 100) {
            n = '0' + n;
        }
        if (n < 10) {
            n = '0' + n;
        }
        return n;
    },
    FormatDate: function (d) {
        return d.getUTCFullYear() + '-' + this.PadZero(d.getUTCMonth() + 1) + '-' + this.PadZero(d.getUTCDate()) + 'T' +
            this.PadZero(d.getUTCHours()) + ':' + this.PadZero(d.getUTCMinutes()) + ':' + this.PadZero(d.getUTCSeconds()) + '.' +
            this.Pad2Zeros(d.getUTCMilliseconds());
    },
    AddStatusMessage: function (msg) {
        var d = new Date();
        $jq("#divRealTimeNotificationStatus").append(this.FormatDate(d) + ":" + msg + "<br/>");
    },
    SubscribeReceive: function (args) {
        var data = null;
        if (args.data) {
            data = args.data;
        } else {
            data = args.getData();
        }

        try
        {
            PeopleMedia.RealTimeNotificationOverlay.AddStatusMessage("Received message: " + fm.json.serialize(data));
        } catch (ex) { }

        PeopleMedia.RealTimeNotificationOverlay.ProcessMessage(data);
    },
    PublishMessageReceived: function (batchInfo) {
        if (batchInfo !== null && batchInfo.BatchGuid !== null) {
            try
            {
                PeopleMedia.RealTimeNotificationOverlay.AddStatusMessage("Sent acknowledgement for batch guid: " + fm.json.serialize(batchInfo.BatchGuid));
            } catch (ex) { }

            this.Client.publish({
                channel: PeopleMedia.RealTimeNotificationOverlay.Channel,
                data: { 'pubtype': 'puack', 'channel': PeopleMedia.RealTimeNotificationOverlay.Channel, 'batchguid': batchInfo.BatchGuid }
            });
        }
    },
    Initialize: function () {
        PeopleMedia.WebSyncServer.Init();
        this.Client = PeopleMedia.WebSyncServer.Client;

        $jq("#close_alert").click(function (event) {
            event.stopPropagation();
            PeopleMedia.RealTimeNotificationOverlay.CloseAlert();
        });
        if (typeof fm !== 'undefined' && PeopleMedia.RealTimeNotificationOverlay.Channel.length > 0) {
            this.Client.subscribe({
                channel: PeopleMedia.RealTimeNotificationOverlay.Channel,
                onReceive: PeopleMedia.RealTimeNotificationOverlay.SubscribeReceive
            });
        }
    }
};